package com.easypay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.easypay.util.RsaUtil;
import com.easypay.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 *  基础支付请求类,提供公共参数和方法信息
 *
 * @date: 2021/10/22 11:31
 * @author: pandans
 */
public class BasePay extends Object{
    /**
     * 收银台请求地址
     */
    public static final String CASHIER_URL = "https://mtest.eycard.cn";
//    public static final String CASHIER_URL = "http://10.10.14.128:8805";
    /**
     * 微收单优化业务请求地址
     */
    public static final String BASE_URL = "https://t-wapi.bhecard.com:8443";
    /**
     * 分账，退货地址
     */
    public static final String BASE_URL_LEDGER = "https://t-wapi.bhecard.com:6111";

    //!!! -------- 1. 生成商户自己生成一对公私钥匙，可到http://www.metools.info/code/c80.html 自行生成，密钥长度选择1024bit --------将公钥给易生进行参数配置////
    //!!! -------- 2. 测试环境为了方便统一由易生直接生成，并将私钥给予到商户

//      商户私钥 BZ0002toORG000000000006.cer
    public static final String BZ0002toORG000000000006 = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOSxfpYzsR5pKg0lpDb8rwhmJuaN06l+o9wf5FvKFoGCGt0yMmv/OUqsiFzuatZ7VV2hx/WavOVVubMr6YXD8/GINStC/6Hj7ih30XDjQLM1TRmBfhux+FO3LEYUULKbp/LZz+tXDU6QN6Hvw3CGNRhwdAV5Sq1d0REg7tbPuCZpAgMBAAECgYBigmpqvN2AogAxJZO08+dZkNcU3ObdzeU7fqlZOJW1N5vmyCacCpZdKjCbB0ASH5JIANYnX34as3CIU1QGAMBk63Rm7LYF7mPu3r+qYUhwt60FTynxktkKgvtr2slDNc+oF4noAKvzd3W752RWn/lp9rGvhkk8gljaBVa0A+4A+QJBAP6R2b7dDdmICLJFJV8EdKJjThndSQymS4MLT2p3ZdT2ULhMtLjbOy0FeQaBFEkF6cy8TquIvO76qwlNCPlO5qcCQQDl+mz7s7Pd6SaMcuAMPDnuCNqVZNspseP3WmnB3q/Bt3Ad+dTtoopVYgvrIAb+VxVkZ804k3c192wl9BilVTxvAkEA4I4jdztjRim7EhXwezpg8AWNFT+femsOXRATA6VCzHJijdAL8qxgLLyRH22pSSjQLetFsgYyMtQnH1M2wUQaLQJBAKNDNa02NKF8C+a3AoENHF70oCBgegnOhLSr1dpQuVr/W7OcEWIl+qiEs0tW8EANGF2wJwtb/Mwt+vOypvBwYzcCQQCff7Cv+JHXx+voggV+lJqkBpFGjIV2axQ97n4JrBxwok7y42KEhMrKqVRAzXp7iGSxXfq7AkL0JSU7gSz+dg/3";


    public static final String MER_RSA_PRIVATE_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAOSxfpYzsR5pKg0lpDb8rwhmJuaN06l+o9wf5FvKFoGCGt0yMmv/OUqsiFzuatZ7VV2hx/WavOVVubMr6YXD8/GINStC/6Hj7ih30XDjQLM1TRmBfhux+FO3LEYUULKbp/LZz+tXDU6QN6Hvw3CGNRhwdAV5Sq1d0REg7tbPuCZpAgMBAAECgYBigmpqvN2AogAxJZO08+dZkNcU3ObdzeU7fqlZOJW1N5vmyCacCpZdKjCbB0ASH5JIANYnX34as3CIU1QGAMBk63Rm7LYF7mPu3r+qYUhwt60FTynxktkKgvtr2slDNc+oF4noAKvzd3W752RWn/lp9rGvhkk8gljaBVa0A+4A+QJBAP6R2b7dDdmICLJFJV8EdKJjThndSQymS4MLT2p3ZdT2ULhMtLjbOy0FeQaBFEkF6cy8TquIvO76qwlNCPlO5qcCQQDl+mz7s7Pd6SaMcuAMPDnuCNqVZNspseP3WmnB3q/Bt3Ad+dTtoopVYgvrIAb+VxVkZ804k3c192wl9BilVTxvAkEA4I4jdztjRim7EhXwezpg8AWNFT+femsOXRATA6VCzHJijdAL8qxgLLyRH22pSSjQLetFsgYyMtQnH1M2wUQaLQJBAKNDNa02NKF8C+a3AoENHF70oCBgegnOhLSr1dpQuVr/W7OcEWIl+qiEs0tW8EANGF2wJwtb/Mwt+vOypvBwYzcCQQCff7Cv+JHXx+voggV+lJqkBpFGjIV2axQ97n4JrBxwok7y42KEhMrKqVRAzXp7iGSxXfq7AkL0JSU7gSz+dg/3";



    public static final String BZ0001toORG000000000004 = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJXJo/EewLmDuTChmfUNtfdSosZnlUESPRyGtpvzEw8nwFrShU2dCckcHiEB5n3yejUArjMtnZhLvwVM6dPoWzczScY8mt8I5IY19Mnf1nzOHUocqFZPLAXHdrRs/tVh77UMQIL810t7czIQ8XQ6MarXborprhM85xSJvHujGXNjAgMBAAECgYAa6rZUQSN+8uXXkGK7P7CAdlAb+Uc//0gOFUNBeQfmxEzzxTsBPIQiqLPdWJsT7Pv7BFlJhxv33zy/dhfa5blmRDd/V7ZxMKidobVnwvnEtIIXawjny6+LuXdHywZKlZhKTkvSumIFjpftE/JQ6jv+lwNLR4HMx6Zk1spVvjwu6QJBAP6RR91W2FRgXLX7+Jl15ePa4J/0yS1C/YvGoGo0CggYkSxjraGHZCQYG46/81ld9i84WbukBIU8GMXgmWTrN48CQQCWoWsQmmmK2aB2A/VfTGcLJwDBDt+Rsp1k5s6Y3VKwkyt4Qoqps8QdC8EEwru1hzzc3KZer4P1ZeRI6LgJ1rztAkEAys0OhWSUPtPtyAUOTaNBG77ZSFUImAhQWTRJw5HllAGOVeCrCI4F10NlYNnGkiFq6L9prTTDbSktSybczSsePQJARjm3SqRStFNFxf+OdAGQwNhMN7WRccHOM26PvyDgHkZeq9CKCRgwREJomKmZDcahD28neVlmsg/w4DTvKFce+QJBAMX5si40GHA+Oabb/YxYuAOv9tNbY4wq14UyjaoCEkWP4EfFR60gN0quv4BIryV7hiCTiGFgJSlJfbCu4vVki1U=";


    /**
     * 商户公钥， 提供给易生,易生对商户的报文进行验签（测试方便，直接由易生提供给商户）
     */
//    public static final String MER_RSA_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVyaPxHsC5g7kwoZn1DbX3UqLGZ5VBEj0chrab8xMPJ8Ba0oVNnQnJHB4hAeZ98no1AK4zLZ2YS78FTOnT6Fs3M0nGPJrfCOSGNfTJ39Z8zh1KHKhWTywFx3a0bP7VYe+1DECC/NdLe3MyEPF0OjGq126K6a4TPOcUibx7oxlzYwIDAQAB";

    public static final String MER_RSA_PUBLIC_KEY =
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDksX6WM7EeaSoNJaQ2/K8IZibmjdOpfqPcH+RbyhaBghrdMjJr/zlKrIhc7mrWe1Vdocf1mrzlVbmzK+mFw/PxiDUrQv+h4+4od9Fw40CzNU0ZgX4bsfhTtyxGFFCym6fy2c/rVw1OkDeh78NwhjUYcHQFeUqtXdERIO7Wz7gmaQIDAQAB";

    /**
     * 易生支付提供的机构公钥  -- 联调支持提供或者文档上拷贝
     */
    public static final String EASYPAY_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAqRw0nZ1rGTpAeKupP7coS+en6BveJL4aFVt9men4Zzkpuv/IeK6YJ2yk4m8ppZ7TLW4t5WsPEhYOnUfMtjhW4nuQfjgU54juJ1KMHYiX9gaaO+z80ZnaiKD2YsZMFiE9dlTeBlkRL5xXbHa+JonHfVKXMr13oI8oZNKdpnvknQIDAQAB";

    /**
     * 默认的接口签名方式
     */
    public static final String SIGN_TYPE_RSA256 = "RSA2";
    public static final String SIGN_TYPE_RSA = "RSA";
//

    // 杰德  (包括付款码)
//    public static final String TEST_ORGID = "ORG000000002856";
//    public static final String TEST_ORGMERCODE = "531000012972421";
//    public static final String TEST_ORGTERMNO = "W1489541";

//    // 259 号改造使用参数
//    public static final String TEST_ORGID = "ORG000000000041";
//    public static final String TEST_ORGMERCODE = "531000012972728";
//    public static final String TEST_ORGTERMNO = "W1489724";
//    public static final String TEST_MER_RSA_PRIVATE_KEY = BZ0001toORG000000000004;

    // 深圳市策城软件有限公司
    public static final String TEST_ORGID = "ORG000000004785";
    public static final String TEST_ORGMERCODE = "531000013010845";
    public static final String TEST_ORGTERMNO = "32812114";
    public static final String TEST_MER_RSA_PRIVATE_KEY = BZ0002toORG000000000006;

    //
//    public static final String TEST_ORGID = "ORG000000007646";
//    public static final String TEST_ORGMERCODE = "531000013007685";
//    public static final String TEST_ORGTERMNO = "32808375";

//    // 林创
//    public static final String TEST_ORGID = "ORG000000000054";
//    public static final String TEST_ORGMERCODE = "531000012972388";
//    public static final String TEST_ORGTERMNO = "W1489518";

    // 助订
//        public static final String TEST_ORGID = "ORG000000000053";
//        public static final String TEST_ORGMERCODE = "531000012972310";
//        public static final String TEST_ORGTERMNO = "W1489510";


    // ORG000000000001
//    public static final String TEST_ORGID = "ORG000000000001";
//    public static final String TEST_ORGMERCODE = "890000000123679";
//    public static final String TEST_ORGTERMNO = "W0616228";


//    // 吉安莞鑫网联有限公司
//    public static final String TEST_ORGID = "ORG000000001212";
//    public static final String TEST_ORGMERCODE = "531000012974414";
//    public static final String TEST_ORGTERMNO = "32774994";

//
//    public static final String TEST_ORGID = "ORG000000000042";
//    public static final String TEST_ORGMERCODE = "531000012972728";
//    public static final String TEST_ORGTERMNO = "W1489724";


    //  付款码 支付
//    public static final String TEST_ORGID = "ORG000000005203";
//    public static final String TEST_ORGMERCODE = "531000012972519";
//    public static final String TEST_ORGTERMNO = "32772674";

//        //上实
//        public static final String TEST_ORGID = "ORG000000000005";
//        public static final String TEST_ORGMERCODE = "531000012972501";
//        public static final String TEST_ORGTERMNO = "W1489580";


//    //  临时测试
//    public static final String TEST_ORGID = "ORG000000005796";
//    public static final String TEST_ORGMERCODE = "531000012973074";
//    public static final String TEST_ORGTERMNO = "32773384";

//    //  临时测试
//    public static final String TEST_ORGID = "ORG000000002856";
//    public static final String TEST_ORGMERCODE = "531000012972421";
//    public static final String TEST_ORGTERMNO = "W1489524";

    //  犇犇牛
//    public static final String TEST_ORGID = "ORG000000001431";
//    public static final String TEST_ORGMERCODE = "531000012972515";
//    public static final String TEST_ORGTERMNO = "32772671";

//    // 和行无限
//    public static final String TEST_ORGID = "ORG000000005863";
//    public static final String TEST_ORGMERCODE = "531000012972561";
//    public static final String TEST_ORGTERMNO = "32772711";



//    // 杭州园钉
//    public static final String TEST_ORGID = "ORG000000001202";
//    public static final String TEST_ORGMERCODE = "531000012973231";
//    public static final String TEST_ORGTERMNO = "32773606";


    // 西安航驰中盛信息科技有限公司
//    public static final String TEST_ORGID = "ORG000000001206";
//    public static final String TEST_ORGMERCODE = "531000012973671";
//    public static final String TEST_ORGTERMNO = "32774123";


    // 宝鸡新城宝物业有限公司
//    public static final String TEST_ORGID = "ORG000000000005";
//    public static final String TEST_ORGMERCODE = "531000012973413";
//    public static final String TEST_ORGTERMNO = "32773827";


//    // 大名城
//    public static final String TEST_ORGID = "ORG000000000005";
//    public static final String TEST_ORGMERCODE = "531000012972932";
//    public static final String TEST_ORGTERMNO = "W1489847";


//    // 河南思迅网络科技有限公司
//    public static final String TEST_ORGID = "ORG000000001204";
//    public static final String TEST_ORGMERCODE = "531000012973473";
//    public static final String TEST_ORGTERMNO = "W1489990";


//    // 陕西迎米生活电商超市有限公司
//    public static final String TEST_ORGID = "ORG000000005203";
//    public static final String TEST_ORGMERCODE = "531000012972519";
//    public static final String TEST_ORGTERMNO = "32772674";


//    // ORG000000000042  微收单优化网页 账号
//    public static final String TEST_ORGID = "ORG000000000042";
//    public static final String TEST_ORGMERCODE = "831135358120001";
//    public static final String TEST_ORGTERMNO = "21120433";





    // 微收单优化   银联云闪付app支付（原手机控件支付）接口
//    public static final String TEST_ORGID = "ORG000000000007";
//    public static final String TEST_ORGMERCODE = "831135358120001";
//    public static final String TEST_ORGTERMNO = "21120433";

    // 长春 二 丫丫
//    public static final String TEST_ORGID = "ORG000000003626";
//    public static final String TEST_ORGMERCODE = "531000012973752";
//    public static final String TEST_ORGTERMNO = "32774242";

    // 上海杨欣设计装设有限公司   原本没分期， 配置之后，有了
//    public static final String TEST_ORGID = "ORG000000001208";
//    public static final String TEST_ORGMERCODE = "531000012973446";
//    public static final String TEST_ORGTERMNO = "W1489984";

    // 测试云H5
//    public static final String TEST_ORGID = "ORG000000001203";
//    public static final String TEST_ORGMERCODE = "531000012973385";
//    public static final String TEST_ORGTERMNO = "32773796";


    // 郑州新鸟网络科技有限公司 (数科)
//    public static final String TEST_ORGID = "ORG000000000042";
//    public static final String TEST_ORGMERCODE = "531000012974340";
//    public static final String TEST_ORGTERMNO = "32774875";


    // 河北冕驰信息技术有限公司
//    public static final String TEST_ORGID = "ORG000000001210";
//    public static final String TEST_ORGMERCODE = "531000012973925";
//    public static final String TEST_ORGTERMNO = "32774502";



////    // 云收银网页测试账号 ORG000000000001    惠付科技 用的这个   有分期     洁测试商户
//    public static final String TEST_ORGID = "ORG000000000001";
//    public static final String TEST_ORGMERCODE = "890000000123679";
//    public static final String TEST_ORGTERMNO = "W0616228";

    // 河北冕驰信息技术有限公司
//    public static final String TEST_ORGID = "ORG000000001210";
//    public static final String TEST_ORGMERCODE = "531000012973925";
//    public static final String TEST_ORGTERMNO = "32774502";

    // 河北华腾
//    public static final String TEST_ORGID = "ORG000000001211";
//    public static final String TEST_ORGMERCODE = "531000012974403";
//    public static final String TEST_ORGTERMNO = "32774982";






    //上实
//        public static final String TEST_ORGID = "ORG000000000005";
//        public static final String TEST_ORGMERCODE = "531000012972501";
//        public static final String TEST_ORGTERMNO = "W1489580";
        // 宝鸡物业
//        public static final String TEST_ORGID = "ORG000000000005";
//        public static final String TEST_ORGMERCODE = "531000012973413";
//        public static final String TEST_ORGTERMNO = "32773827";

    // 西安航驰中盛
//    public static final String TEST_ORGID = "ORG000000001206";
//    public static final String TEST_ORGMERCODE = "531000012973671";
//    public static final String TEST_ORGTERMNO = "32774123";

    // 云易收请使用：
    /**
     * 机构ID -- 联调支持分配
     */
    public static final String ORGID = TEST_ORGID;
    /**
     * 机构商户号 -- 联调支持分配
     */
    public static final String ORGMERCODE = TEST_ORGMERCODE;
    /**
     * 机构终端号 -- 联调支持分配
     */
    public static final String ORGTERMNO = TEST_ORGTERMNO;

    /**
     * 接口返回成功代码
     */
    public static final String RET_CODE_SUCCESS = "000000";




    public static final String ORGLedgerMERCODE = "531000012972421";
    public static final String ORGLedgerTERMNO = "W1489524";


    /**
     * 排序拼接需要签名的数据， ！！参数值不为空且trim不为空。
     *
     * @param dataObj 数据对象 不能都为空
     * @return 签名排序字符串
     */
    public static String getReqStr(Object dataObj) {

        JSONObject data = (JSONObject) JSON.toJSON(dataObj);

//        data = JSONObject.parseObject("{\"tradeAmt\":\"9\",\"orgBackUrl\":\"https://pay-test.jian9999.cn/gateway/notify/EASYPAYALIPAY\",\"splitSettleFlag\":\"1\",\"payerId\":\"123123123\",\"orderInfo\":\"购买苹果手机一个\",\"tradeCode\":\"WUJS1\"}");

        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            // 参数值为空，则不参与签名
            if (data.get(k) != null && data.get(k).toString().trim().length() > 0) {
                sb.append(k).append("=").append(data.get(k).toString().trim()).append("&");
            }
        }
        return sb.substring(0, sb.toString().lastIndexOf("&"));
    }

    /**
     * 验证易生返回的报文数据. !!!使用data字段的内容验签
     *
     * @param response 易生返回的数据
     * @return 验签是否成功
     */
    public static boolean checkSign(String response) {
        JSONObject json = JSON.parseObject(response);
        // 云易收sysRetCode 和 微收单 sysRetcode
        if ("000000".equals(json.getString("sysRetcode")) || "000000".equals(json.getString("sysRetCode"))) {
            String sign = json.getString("sign");
            if (StringUtils.isEmpty(sign)) {
                System.out.println("=====> 签名失败，该报文未返回签名数据");
                return false;
            }
            JSONObject jsonData = json.getJSONObject("data");
            boolean ret = RsaUtil.verifyBySHA256WithRSA(getReqStr(jsonData), sign, EASYPAY_PUBLIC_KEY);

            if (ret) {
                System.out.println("=====> 验签成功，接口数据安全");
                return true;
            } else {
                System.out.println("=====> 验签失败，请注意报文安全");
                return false;
            }
        } else {
            System.out.println("=====> 非00状态码，不需要验签");

            return false;
        }
    }
    public static boolean checkBizSign(String response) {
        JSONObject json = JSON.parseObject(response);
        // 云易收sysRetCode 和 微收单 sysRetcode
        if ("000000".equals(json.getString("sysRetcode")) || "000000".equals(json.getString("sysRetCode"))) {
            String sign = json.getString("sign");
            if (StringUtils.isEmpty(sign)) {
                System.out.println("=====> 签名失败，该报文未返回签名数据");
                return false;
            }
            JSONObject jsonData = json.getJSONObject("bizData");
            boolean ret = RsaUtil.verifyBySHA256WithRSA(getReqStr(jsonData), sign, EASYPAY_PUBLIC_KEY);

            if (ret) {
                System.out.println("=====> 验签成功，接口数据安全");
                return true;
            } else {
                System.out.println("=====> 验签失败，请注意报文安全");
                return false;
            }
        } else {
            System.out.println("=====> 非00状态码，不需要验签");

            return false;
        }
    }

    /**
     * 使用商户的私钥进行加签
     *
     * @param data: 签名数据，注意这里仅仅是文档中data字段的内容
     * @return java.lang.String 签名
     */
    public static String sign(Object data, String signKey) {
        String reqStr = getReqStr(data);

        String res = RsaUtil.signBySHA256WithRSA(reqStr, signKey);


//        System.out.println("\n==========================================================签名过程 开始==========================================================" + "\n【签名KEY：】" + MER_RSA_PRIVATE_KEY + "\n\n【原始数据：】" + data + "\n【真正签名的数据：】" + reqStr + "\n【签名后的值：】" + res + "\n==========================================================签名过程 结束==========================================================\n");

        return res;
    }

    public static String signStr(String data, String signKey) {
        return sign(JSON.parseObject(data), signKey);
    }

//    public static String checkSign(content) {
//        String reqStr = getReqStr(data);
//
//        String res = RsaUtil.verifyBySHA256WithRSA()
//
//
//        System.out.println("\n==========================================================签名过程 开始==========================================================" + "\n【签名KEY：】" + MER_RSA_PRIVATE_KEY + "\n\n【原始数据：】" + data + "\n【真正签名的数据：】" + reqStr + "\n【签名后的值：】" + res + "\n==========================================================签名过程 结束==========================================================\n");
//
//        return res;
//    }



//    Map map = new HashMap<>();
//        map.put("name", "zs");
//        map.put("age", 20);
//
//    String sign = sign(map);
//
//    System.out.println(sign);
}
